package com.xpsoft.oa.workflow.event;

import java.util.Date;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jbpm.api.listener.EventListener;
import org.jbpm.api.listener.EventListenerExecution;
import org.jbpm.api.model.OpenProcessInstance;

import com.xpsoft.core.util.AppUtil;
import com.xpsoft.oa.model.flow.ProcessRun;
import com.xpsoft.oa.model.produce.MaterialDivert;
import com.xpsoft.oa.model.system.AppUser;
import com.xpsoft.oa.service.flow.ProcessRunService;
import com.xpsoft.oa.service.produce.MaterialDivertService;
import com.xpsoft.oa.service.project.ProjectService;
import com.xpsoft.oa.service.system.AppUserService;

public class MaterialDivertFinishListener implements EventListener{
	private Log logger=LogFactory.getLog(MaterialDivertFinishListener.class);
	@Override
	public void notify(EventListenerExecution execution) throws Exception {
		//获取表单参数
		OpenProcessInstance pi=execution.getProcessInstance();
		String fromRepertory = (String)pi.getVariable("materialDivert.fromRepertory");
		String fromProjectId = (String)pi.getVariable("materialDivert.fromProject.id");
		String toProjectId = (String)pi.getVariable("materialDivert.toProject.id");
		Date divertDate = (Date)pi.getVariable("materialDivert.divertDate");
		String divertReason = (String)pi.getVariable("materialDivert.divertReason");
		String dataList = (String)pi.getVariable("materialDivert.dataList");
		boolean isProjectRep = true;
		MaterialDivert materialDivert = new MaterialDivert();
		materialDivert.setFromRepertory(fromRepertory);
		materialDivert.setDivertDate(divertDate);
		materialDivert.setDivertReason(divertReason);

		ProjectService projectService = (ProjectService)AppUtil.getBean("projectService");
		if(StringUtils.isNotBlank(fromProjectId)){
			materialDivert.setFromProject(projectService.get(Long.valueOf(fromProjectId)));
			isProjectRep = true;
		}
		if(StringUtils.isNotBlank(toProjectId)){
			materialDivert.setToProject(projectService.get(Long.valueOf(toProjectId)));
			isProjectRep = false;
		}
		
		ProcessRunService processRunService=(ProcessRunService)AppUtil.getBean("processRunService");
		ProcessRun processRun=processRunService.getByExeId(pi.getId());
		materialDivert.setProcessRunId(processRun.getRunId());
		
		MaterialDivertService materialDivertService = (MaterialDivertService)AppUtil.getBean("materialDivertService");
		materialDivertService.saveMaterialDivert(materialDivert, dataList,isProjectRep);
		
		
		//获取流程发起者对象
		AppUser flowStartUser=(AppUser)execution.getProcessInstance().getVariable("flowStartUser");
	
		//所有参与流程的都发消息
		AppUtil.sendSysShortMsg(execution.getProcessInstance().getId(), flowStartUser);
	}

}
